# -*- encoding: utf-8 -*-
# @Author：lijinxi
# @Time ：2020/12/1 16:05
# @File：database.py
import hashlib
import sqlite3
import os


class DataBase:
    def __init__(self):
        self.user_database = 'user.db'

    # 创建表
    def create_if_not_exist(self):
        if not os.path.exists(self.user_database):
            conn = sqlite3.connect(self.user_database)
            cursor = conn.cursor()
            cursor.execute(
                '''create table if not exists users(username varchar(20) primary key not null, password varchar (20))''')
            cursor.close()
            conn.close()

    # 添加用户
    def add_user(self, username, password):
        conn = sqlite3.connect(self.user_database)
        cursor = conn.cursor()
        # sha1加密
        sha = hashlib.sha1()
        sha.update(password.encode('utf-8'))
        password = sha.hexdigest()
        print(password)
        cursor.execute('insert into users(username,password) values(?,?) ', (username, password))
        conn.commit()
        cursor.close()
        conn.close()

    # 查询用户
    def query_user(self, username, password):
        conn = sqlite3.connect(self.user_database)
        cursor = conn.cursor()
        cursor.execute('select * from  users where username=?', (username,))

        res = cursor.fetchall()
        if len(res) == 0:
            return '该用户不存在, 将拒绝此次连接', 'use_not_exist'
        else:
            # sha1加密后结果比较
            sha = hashlib.sha1()
            sha.update(password.encode('utf-8'))
            password = sha.hexdigest()
            print(password)
            if not password == res[0][1]:
                return '用户和密码不匹配, 请重试', 'authorized_fail'
            else:
                return '登陆成功', 'OK'


if __name__ == '__main__':
    database = DataBase()
    database.create_if_not_exist()
    database.add_user('ftpuser', '12345')
    msg, status_code = database.query_user('ftpuser', '12345')
    print(msg)
